package com.t235.gc.goods.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.t235.gc.AjaxResult;
import com.t235.gc.entity.Goods;
import com.t235.gc.entity.GoodsCategory;
import com.t235.gc.goods.service.GoodsService;
import com.t235.gc.goods.utils.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @PostMapping("/list")
    public AjaxResult find(String goodsCategoryName,Integer pageNo,Integer pageSize){
        pageNo = pageNo == null ? 1 :pageNo;
        pageSize = pageSize == null ? 2 : pageSize;
        PageHelper.startPage(pageNo,pageSize);
        List<GoodsCategory> goodsCategories=goodsService.find(goodsCategoryName);
        PageInfo<GoodsCategory> pageInfo=new PageInfo<>(goodsCategories);
        if(pageInfo!=null){
            return AjaxResult.success();
        }else{
            return AjaxResult.error("10001");
        }

    }

    @PostMapping("/save")
    public AjaxResult save(GoodsCategory goodsCategory){
        RandomUtils ran=new RandomUtils();
        String num=ran.random(16);
        Long sum=Long.parseLong(num);
        goodsCategory.setGoodsCategoryId(sum);
        goodsCategory.setCname("admin");
        goodsCategory.setCtime(new Date());
        int mum= (int) goodsService.save(goodsCategory);
        if(mum>0){
            return AjaxResult.success();
        }else {
            return AjaxResult.error("10001");
        }

    }

    @PostMapping("/del")
    public AjaxResult del(Long goodsCategoryId){
        System.out.println(goodsCategoryId);
        goodsService.update(goodsCategoryId);
        return AjaxResult.success(goodsService.del(goodsCategoryId));
    }

    @PostMapping("/update")
    public AjaxResult update(String goodsCategoryName, String goodsCategoryId){
        System.out.println(goodsCategoryId);
        System.out.println(goodsCategoryName);
        int num = (int) goodsService.upd(goodsCategoryId,goodsCategoryName);
        if(num > 0){
            return AjaxResult.success();
        }else{
            return AjaxResult.error("100003");
        }

    }

}
